/**
 * Created by WYH on 17/4/23.
 */
angular.module('tribalc').controller('LocksAuthController', [
    '$scope', '$stateParams', '$state','Api','Alert',
    function ($scope, $stateParams, $state, Api,Alert) {


        setupSelectedLock();

        $scope.goBack = goback;


        $scope.submitAuthCompany = submitAuthCompany;

        function setupSelectedLock() {
            if (!$stateParams.selectLock || Object.getOwnPropertyNames($stateParams.selectLock).length == 0) {
                Alert.alertBox('未选择设备');
                $state.go('company.managerLocks');
            } else {
                $scope.selectedLock = $stateParams.selectLock;
                getAuthCompanyList($scope.selectedLock.id);
            }
        }


        function getAuthCompanyList(lockId) {
            Api.getAuthAndUnAuthCompanyList(lockId, function (result) {
                $scope.authCompanyList = result.data.authorizedCompanyMembers;
                $scope.unAuthCompanyList = result.data.unauthorizedCompanyMembers;
            });
        }


        function goback() {
            $state.go('company.managerLocks');
        }


        function submitAuthCompany() {
            var companyIdArr = getCompanyIdArr($scope.authCompanyList);
            Api.lockAuthCompany($scope.selectedLock.id, companyIdArr, function (result) {
                Alert.alertBox('授权成功',null);
                goback();
            })
        }


        function getCompanyIdArr(companyArr) {
            var companyIdArr = [];
            companyArr.forEach(function (company) {
                companyIdArr.push(company.id);
            });
            return companyIdArr;
        }

    }
]);